package com.elinkway.infinitemovies.view;

import android.app.Activity;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.RelativeLayout;

import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import com.elinkway.infinitemovies.async.ThirdAdReportTask;
import com.elinkway.infinitemovies.bean.HzPayload;
import com.elinkway.infinitemovies.bean.NewAdDataBean;
import com.elinkway.infinitemovies.bean.RecommendBase;
import com.elinkway.infinitemovies.bean.SDKPayload;
import com.elinkway.infinitemovies.bean.ServerPayload;
import com.elinkway.infinitemovies.bean.TtPayload;
import com.elinkway.infinitemovies.bean.XfPayload;
import com.elinkway.infinitemovies.bean.YzPayload;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.le123.ysdq.R;
import com.le123.ysdq.databinding.HomeFocusItemBinding;
import com.le123.ysdq.databinding.LayoutAdFocusItemBinding;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.recyclerlayout.refresh.MyMessageEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SlideImageView extends RelativeLayout implements View.OnClickListener {

    private SliderLayout mSliderLayout;
    private PagerIndicator mPagerIndicator;

    private boolean mAutoCycle = false;
    private boolean mIsAutoCycling = false;

    private List mDataList = new ArrayList();

    public static interface OnSliderListener {
        void onSliderClick(Object object);

        String getImageUrl(Object object);
    }

    public SlideImageView(Context context) {
        this(context, null);
    }

    public SlideImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlideImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        findViews();
    }

    private void findViews() {
        mSliderLayout = (SliderLayout) findViewById(R.id.slider);
        mSliderLayout.setPresetTransformer(SliderLayout.Transformer.Accordion);
        mSliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
        mSliderLayout.setCustomAnimation(new DescriptionAnimation());
        mPagerIndicator = (PagerIndicator) findViewById(R.id.indicator);
        mSliderLayout.setCustomIndicator(mPagerIndicator);
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                startAutoCycle();
            }
        });
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        startAutoCycle();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopAutoCycle();
        EventBus.getDefault().unregister(this);
    }

    private void startAutoCycle() {
        if (mSliderLayout != null) {
            if (mAutoCycle) {
                if (!mIsAutoCycling) {
                    mIsAutoCycling = true;
                    mSliderLayout.startAutoCycle(5000, 5000, false);
                }
            } else {
                mIsAutoCycling = false;
                mSliderLayout.stopAutoCycle();
            }
        }
    }

    private void stopAutoCycle() {
        if (mSliderLayout != null) {
            mIsAutoCycling = false;
            mSliderLayout.stopAutoCycle();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MyMessageEvent event) {
        if(event.getNumber() == 2){
           stopAutoCycle();
        }
    };

    public void load(Activity activity, List list, ImageLoader imageLoader, String mBDPageIndex, final OnSliderListener listener) {
        if (list == null || list.size() == 0) {
            return;
        }
        if (list.size() > 1) {
            mAutoCycle = true;
        }
        if (mDataList.equals(list)) {
            return;
        }
        mDataList.clear();
        mSliderLayout.removeAllSliders();
        mDataList.addAll(list);
        mAutoCycle = mDataList.size() > 1 ? true : false;
        for (int i = 0; i < mDataList.size(); i++) {
            Object topic = mDataList.get(i);
            if(topic instanceof RecommendBase){
                ((RecommendBase) topic).setCurrentShowIndex(i);
                final RecommendBase item = (RecommendBase) topic;
                CustomSliderView sliderView = new CustomSliderView(activity, item, imageLoader, mBDPageIndex);
                sliderView.setScaleType(BaseSliderView.ScaleType.FitCenterCrop);
                sliderView.setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
                    @Override
                    public void onSliderClick(BaseSliderView slider) {
                        listener.onSliderClick(item);
                    }
                });
                mSliderLayout.addSlider(sliderView);
            }else if(topic instanceof NewAdDataBean){
                AdSliderView adView = new AdSliderView(activity, (NewAdDataBean) topic);
                mSliderLayout.addSlider(adView);
                final NewAdDataBean finalAdBean = (NewAdDataBean) topic;
                final Context finalContext = activity;
                mSliderLayout.addOnPageChangeListener(new ViewPagerEx.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        if(Utils.HZ_AD.equals(finalAdBean.provider) && mSliderLayout.getCurrentSlider() instanceof AdSliderView && finalAdBean.isShow){
                            ArrayList<String> adShowReportUrls = ((HzPayload)finalAdBean.payload).ad.imp;
                            if(adShowReportUrls != null && adShowReportUrls.size() > 0){
                                for (int i=0;i<adShowReportUrls.size();i++){
                                    if(!TextUtils.isEmpty(adShowReportUrls.get(i))){
                                        new ThirdAdReportTask(finalContext, adShowReportUrls.get(i)).start();
                                    }
                                }
                            }
                            HashMap<String, String> gdtPropertyMap = new HashMap<>();
                            gdtPropertyMap.put("position", "focus");
                            UmengEventPoster.doPost(UmengEventPoster.HZSERVERAD_SHOW, gdtPropertyMap);
                            mSliderLayout.removeOnPageChangeListener(this);
                        }else if(Utils.XF_AD.equals(finalAdBean.provider) && mSliderLayout.getCurrentSlider() instanceof AdSliderView && finalAdBean.isShow){
                            ArrayList<String> adShowReportUrls = ((XfPayload)finalAdBean.payload).ad.batch_ma.impr_url;
                            if(adShowReportUrls != null && adShowReportUrls.size() > 0){
                                for (int i=0;i<adShowReportUrls.size();i++){
                                    if(!TextUtils.isEmpty(adShowReportUrls.get(i))){
                                        new ThirdAdReportTask(finalContext, adShowReportUrls.get(i),Utils.getBrowserUa(finalContext)).start();
                                    }
                                }
                            }
                            HashMap<String, String> gdtPropertyMap = new HashMap<>();
                            gdtPropertyMap.put("position", "focus");
                            UmengEventPoster.doPost(UmengEventPoster.XFSERVERAD_SHOW, gdtPropertyMap);
                            mSliderLayout.removeOnPageChangeListener(this);
                        }
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }
        }
        mSliderLayout.setPresetTransformer(SliderLayout.Transformer.Default);
        startAutoCycle();
    }

    public class CustomSliderView extends BaseSliderView {

        public RecommendBase bean;
        public ImageLoader imageLoader;
        public String mBDPageIndex;
        private Activity activity;
        private boolean isReported;

        public CustomSliderView(Context context, RecommendBase bean, ImageLoader imageLoader, String mBDPageIndex) {
            super(context);
            this.bean = bean;
            this.activity = (Activity) context;
            this.imageLoader = imageLoader;
            this.mBDPageIndex = mBDPageIndex;
        }

        @Override
        public View getView() {
            final HomeFocusItemBinding binding = DataBindingUtil.inflate(
                    LayoutInflater.from(getContext()),
                    R.layout.home_focus_item,
                    null,
                    false);
            isReported = false;
            View root = binding.getRoot();
            root.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    if (mOnSliderClickListener != null) {
                        mOnSliderClickListener.onSliderClick(CustomSliderView.this);
                    }
                }
            });
            binding.focusItemImage.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if(binding.focusItemImage.getDrawable() != null){
                        if(!isReported){
                            if(UIs.isOnScreen(activity, SlideImageView.this, mBDPageIndex)){
                                isReported = true;
                                String reportKey = BigDataConstants.AD_HOME_FOCUS_ + String.valueOf(bean.getCurrentShowIndex() + 1) + BigDataConstants._SHOW;
                                Map<String, String> dataMap = BigDataApi.createDataMap(BigDataConstants.ACODE_EXPOSURE, "recnum=focus","0","-","","-");
                                dataMap.put("rank", bean.getCurrentShowIndex() + 1+"");
                                dataMap.put("cur_url", mBDPageIndex);
                                BigDataApi.bigDataCommonReport(dataMap, mContext);
                                UmengEventPoster.doEventPost(reportKey);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                    binding.focusItemImage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                                }else{
                                    binding.focusItemImage.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                                }
                            }
                        }
                    }
                }
            });
            if(!TextUtils.isEmpty(bean.getPic())){
                imageLoader.displayImage(bean.getPic(), binding.focusItemImage);
            }
            if(!TextUtils.isEmpty(bean.getName())){
                binding.focusItemTv.setText(bean.getName());
            }
            return root;
        }
    }

    public class AdSliderView extends BaseSliderView {

        public LayoutAdFocusItemBinding binding;
        private Activity activity;

        public AdSliderView(Context context, NewAdDataBean adBean) {
            super(context);
            activity = (Activity) context;
            binding = DataBindingUtil.inflate(
                    LayoutInflater.from(getContext()),
                    R.layout.layout_ad_focus_item,
                    null,
                    false);
            setAdData(adBean);
        }

        @Override
        public View getView() {
            View root = binding.getRoot();
            return root;
        }

        public void setAdData(NewAdDataBean adBean){
            if(Utils.GDT_AD.equals(adBean.provider)){
                GdtNativeAdView adtAd = new GdtNativeAdView(activity, "focus", binding.getRoot(), "focus");
                adtAd.loadAD(((SDKPayload)adBean.payload).adId);
            }else if(Utils.BAIDU_AD.equals(adBean.provider)){
                BaiduNativeAdView baiduAd = new BaiduNativeAdView(activity, binding.getRoot(), "focus");
                baiduAd.setBaiduAd(((SDKPayload)adBean.payload).adId);
            }else if(Utils.SERVER_AD.equals(adBean.provider)){
                final ServerPayload serverPayload = (ServerPayload) adBean.payload;
                ServerNativeAdView serverAd = new ServerNativeAdView(activity, binding.getRoot(), "focus");
                serverAd.setServerAd(serverPayload, MoviesHttpApi.FOCUS_BANNER);
            }else if (Utils.HZ_AD.equals(adBean.provider)) {
                HzPayAdView hzAdView = new HzPayAdView(activity, binding.getRoot(), "focus");
                hzAdView.setHzAd(((HzPayload)adBean.payload).ad);
            } else if (Utils.YZ_AD.equals(adBean.provider)) {
                YzPayAdView yzAdView = new YzPayAdView(activity, binding.getRoot(), "focus");
                yzAdView.setYzAd(((YzPayload)adBean.payload).ad);
            }else if (Utils.XF_AD.equals(adBean.provider)) {
                XfPayAdView xfAdView = new XfPayAdView(activity, binding.getRoot(), "focus");
                xfAdView.setXfAd(((XfPayload)adBean.payload).ad);
            } else if (Utils.TT_AD.equals(adBean.provider)) {
                TtPayAdView ttAdView = new TtPayAdView(activity, binding.getRoot(), "focus");
                ttAdView.setTtAd(((TtPayload)adBean.payload).ad);
            }
        }
    }
}


